#include "image_manager.h"

// Default constructor for class ImageManager
ImageManager::ImageManager()
{
	sf::Image* placeholder = new sf::Image(5, 5, sf::Color(255, 0, 0));
	ImageMeta placeholder_meta = {"$placeholder"};
	
	this->images.push_back(placeholder);
	this->images_meta.push_back(placeholder_meta);
}

// Destructor for class ImageManager
ImageManager::~ImageManager()
{
	for(std::vector<sf::Image*>::iterator iterator = images.begin();
			iterator != images.end(); ++iterator)
	{
		delete *iterator;
	}
	
}

// function set_image()
//  - Loads an image from a file and push back on std::vector<sf::Image> images;
//  - Returns true if load succeeds, false if load fails
bool ImageManager::set_image(const std::string filename)
{
	// Create new SFML image
	sf::Image* new_image = new sf::Image;
	ImageMeta new_image_meta;
	new_image_meta.filename = filename;
	
	// Load and if loading fails return false
	if(new_image->LoadFromFile(filename) == false)
	{
		return false;	
	}
	// If load succeeds push image back on std::vector<sf::Image> images and return true
	else
	{		
		this->images.push_back(new_image);
		this->images_meta.push_back(new_image_meta);
		return true;
	}
}

// function get_image()
//  - Fetches an image stored in the vector based on the filename
//  - Returns a pointer to the image
sf::Image* ImageManager::get_image(const std::string filename) const
{
	int image_key = 0;
	int loop_count = 0; // variable to count loop, will refer to image_key
	for(std::vector<ImageMeta>::const_iterator iterator = images_meta.begin();
			iterator != images_meta.end(); ++iterator, ++loop_count)
	{
		if( (*iterator).filename == filename )
		{
			image_key = loop_count;
			break;
		}
	}
	
	return this->images.at(image_key);
}